import React, {MouseEvent, useRef, useState} from 'react';
import {Button, message, Popconfirm, Space, Typography} from 'antd';
import type {ProColumns} from '@ant-design/pro-table';
import ProTable, {ActionType} from '@ant-design/pro-table';
import styles from './split.less';
import {loadOrgList, removeOrg} from "@/pages/Enterprise/Org/service";
import {OrgItem} from "@/pages/Enterprise/Org/data";
// import {useModel} from "@@/plugin-model/useModel";
const {Text} = Typography;

type OrgListProps = {
  simpleMode?: boolean;
  onChange: (item: OrgItem) => void;
  onDataLoad?: (dataList: OrgItem[]) => void;
  onAction?: (item: OrgItem, mode: string) => void;
  actionRef?: React.Ref<ActionType | undefined>;
};

const OrgList: React.FC<OrgListProps> = (props) => {
  // const {initialState} = useModel('@@initialState');
  // const [access] = useState(initialState?.currentUser?.access || "");

  const {onChange, onDataLoad, onAction, simpleMode, actionRef: propsActionRef} = props;
  const clickAction = (e: MouseEvent, item: OrgItem, action: string) => {
    onAction && onAction(item, action);
    stopAction(e);
  }

  const stopAction = (e?: MouseEvent) => {
    if (e) {
      e.stopPropagation();
      e.preventDefault();
    }
  }
  // useImperativeHandle(propsActionRef, () => actionRef.current);
  const actionRef = useRef<ActionType>();
  if (propsActionRef) {
    // @ts-ignore
    propsActionRef.current = actionRef.current;
  }
  const [orgId, setOrgId] = useState(0);

  const handleRemove = async (orgId: number) => {
    const hide = message.loading('正在删除');
    if (!orgId) return true;

    try {
      await removeOrg(orgId);
      hide();
      message.success('删除成功，即将刷新');
      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  const columns: ProColumns<OrgItem>[] = [
    {
      title: '部门名称',
      key: 'label',
      dataIndex: 'label',
      // align:"center",
      // copyable: true,
      render: (text, record, index) => (
        <Space>
          <Text copyable={{text: record.label + ":" + record.id}}> {text}</Text>
        </Space>
      )
    },
    {
      title: '状态',
      key: 'status',
      dataIndex: 'status',
      hideInTable: simpleMode,
      valueEnum: {
        0: {
          text: '正常',
          status: 'Success',
        },
        1: {
          text: '禁用',
          status: 'Error',
        },
      },
    },
    {
      title: '操作',
      key: 'option',
      hideInTable: simpleMode,
      valueType: 'option',
      render: (dom, entity) => [
        <a
          key="edit-org"
          onClick={(e) => {
            clickAction(e, entity, 'edit')
          }}
        >
          修改
        </a>,
        <Popconfirm
          key="remove-org"
          okButtonProps={{danger: true}}
          title={`确认删除部门：${entity.label}?`}
          onConfirm={async (e) => {
            await handleRemove(entity.id)
            actionRef.current?.reloadAndRest?.();
            stopAction(e);
          }}
          onCancel={stopAction}
          okText="删除"
          cancelText="取消"
        >
          <a href="#" onClick={stopAction}> 删除 </a>
        </Popconfirm>,

        <a key="add-org" onClick={(e) => {
          clickAction(e, entity, 'add')
        }}>
          添加子部门
        </a>,
      ],
    },
  ];
  const [defaultExpanded, setDefaultExpanded] = useState([])

  return (
    <ProTable<OrgItem>
      actionRef={actionRef}
      columns={columns}
      request={async (params, a, c) => {
        const result = await loadOrgList(simpleMode ? {'status': '0'} : {});
        let newExpandedKeys: any[];
        newExpandedKeys = [];
        const render = (data: OrgItem[]) => { // 获取到所有可展开的父节点
          data.map(item => {
            if (item.children) {
              newExpandedKeys.push(item.id)
              render(item.children)
            }
          })
          return newExpandedKeys
        }
        // setDataList(result.data);
        setDefaultExpanded(render(result.data) as []);
        onDataLoad && onDataLoad(result.data);
        console.log(result.data);
        return {
          data: result.data,
          success: true,
        };
      }}
      rowKey="id"
      rowClassName={(record) => {
        return record.id === orgId ? styles['split-row-select-active'] : '';
      }}
      headerTitle={"部门列表"}
      toolbar={{
        actions: simpleMode ? [] : [
          <Button key="list" type="primary" onClick={(e) => clickAction(e, {
            label: "",
            parentId: 0,
            status: "",
            weight: 0,
            id: 0
          }, 'add')}>
            新建部门
          </Button>,
        ],
      }}
      expandable={{expandedRowKeys: defaultExpanded}}
      search={false}
      options={false}
      pagination={false}

      onRow={(record) => {
        return {
          onClick: () => {
            setOrgId(record.id)
            onChange(record);
          },
        };
      }}
    />
  );
};
export default OrgList;
